//
//  GalleryVideosViewController.m
//  RtspClient
//
//  Created by qi tan on 2024/3/4.
//  Copyright © 2024 Andres Rojas. All rights reserved.
// 视频显示页面。

#import "GalleryVideosViewController.h"
#import "VideoCell.h"
#import <AssetsLibrary/AssetsLibrary.h> // 必须导入
#import <Photos/Photos.h>

#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVKit/AVKit.h> // ios9,视频播放
// 9中播放视频，需要的框架。


@interface GalleryVideosViewController () <UITableViewDataSource, UITableViewDelegate >

@property (weak, nonatomic) IBOutlet UITableView *tableView00;
// 数据源
@property(nonatomic, strong) NSMutableArray *videos; // 视频列表
@property (strong,nonatomic)AVPlayer *player;
@end


@implementation GalleryVideosViewController
#pragma mark 懒加载数据
-(void)initDataList {
    NSString * tmpDir = NSTemporaryDirectory();
   NSFileManager *fileManager = [NSFileManager defaultManager];
   // 获取目录下的所有文件名数组
   NSError *error;
   NSArray *subPaths = [fileManager contentsOfDirectoryAtPath:tmpDir error:&error];
   
   NSArray *sorted = [subPaths sortedArrayUsingComparator:^NSComparisonResult(NSString *firstPath,NSString *secondPath) {
       NSString *firstUrl = [tmpDir stringByAppendingPathComponent:firstPath];
       NSString *secondUrl = [tmpDir stringByAppendingPathComponent:secondPath];
       
       NSDictionary *firstFileInfo = [[NSFileManager defaultManager]
                                      attributesOfItemAtPath:firstUrl error:nil];
       NSDictionary *secondFileInfo = [[NSFileManager defaultManager]
                                       attributesOfItemAtPath:secondUrl error:nil];
       id firstData = [firstFileInfo objectForKey:NSFileCreationDate];
       id secondData = [secondFileInfo objectForKey:NSFileCreationDate];
       return [secondData compare:firstData];
   }];
   NSMutableArray * array00 = [NSMutableArray array];
   for (NSString *fileName2 in sorted) {
       if([fileName2 hasSuffix:@".mp4"]) { // 视频
           [array00 addObject: fileName2];
       }
   }
   _videos = array00;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle: NSLocalizedString(@"gallery_videos", nil)];
    [self initDataList]; // 初始化数据
    self.tableView00.dataSource = self;
    self.tableView00.delegate = self;
    self.tableView00.rowHeight = 94;
    [self.tableView00 reloadData];
}

#pragma mark 列表侧滑删除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if(editingStyle == UITableViewCellEditingStyleDelete) {
        // 删除item操作。
        [self showDeleteDialog:tableView withIndexPath: indexPath];
    }
}
// TODO 无效方法 delete
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:( NSIndexPath *)indexPath{
    return NSLocalizedString(@"delete", nil);
}

// 二次弹框，确认删除 sure_to_delete
- (void)showDeleteDialog:(UITableView *)tableView withIndexPath:(NSIndexPath *) indexPath {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"prompt", nil)
        message:NSLocalizedString(@"sure_to_delete", nil)
        preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil)
                                                           style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"confirm", nil)
                                                       style:UIAlertActionStyleDefault
                                                     handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"row: %zd", indexPath.row);
            
            [self deleteTempDirFile:self.videos[indexPath.row]]; // 先删除原始集合中数据
            [self.videos removeObjectAtIndex:indexPath.row];
           
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
        
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

// 删除临时文件夹中的视频文件
-(void)deleteTempDirFile:(NSString *)fileName{
    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
    NSFileManager *fmgr = [NSFileManager defaultManager];
    BOOL result = [fmgr removeItemAtPath:filePath error:nil];
    if(result){
        NSLog(@"删除视频元素: %@", fileName);
    } else {
        NSLog(@"删除视频失败: %@", fileName);
    }
}
#pragma mark 列表数据源方法。
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.videos.count;
}
// 列表item的显示样式。bug
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 1.获取模型数据
    NSString *model = nil;
    VideoCell *cell = nil;
    if(indexPath.row < self.videos.count) {
        model = self.videos[indexPath.row];
        cell = [VideoCell videoImageCellWithTableView:self.tableView00];
    }
    // 使用xib方式，创建自定义view
    cell.item = model;
    return cell;
}

#pragma mark 列表cell选择
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    NSString * fileName = self.videos[indexPath.row];
    NSLog(@"选择ship: %@", fileName);
    // 点击视频item 后，进入视频播放界面。
    NSString *path =[NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
    NSURL *nsUrl = [NSURL fileURLWithPath:path];
    [self playVideo9WithNSURL:nsUrl];

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


// iOS9 版本的视频播放。AVPlayer
-(void)playVideo9WithNSURL: (NSURL*) url{
    AVPlayerViewController *pvc = [AVPlayerViewController new];
//    NSURL *url = [[NSBundle mainBundle] URLForResource:@"7_1708680983.mp4" withExtension:nil];
    pvc.player = [AVPlayer playerWithURL:url];
    [pvc.player play]; // 开始播放
    
    // 模态弹出, 模态弹出要等view显示之后。应该在视图出现之后，调用。
    [self presentViewController:pvc animated:YES completion:nil];
    // 如果要自定义播放器的大小，应该自定义，设置frame，添加到视图中。
}

@end
